const momentService = require("../service/moment.service");

class MomentController {
  async create(ctx, next) {
    const { content } = ctx.request.body;

    const { id } = ctx.user;

    const result = await momentService.create(content, id);

    ctx.body = {
      code: 0,
      message: "创建成功",
      data: result,
    };
  }

  async list(ctx, next) {
    const { offset, size } = ctx.query;

    const result = await momentService.queryList(offset, size);

    ctx.body = {
      code: 0,
      message: "查询成功",
      data: result,
    };
  }

  async detail(ctx, next) {
    const { momentId } = ctx.params;
    const result = await momentService.queryById(momentId);
    ctx.body = {
      code: 0,
      data: result[0],
    };
  }

  async remove(ctx, next) {
    const { momentId } = ctx.params;
    const result = await momentService.remove(momentId);
    ctx.body = {
      code: 0,
      message: "删除成功",
      data: result,
    };
  }

  async update(ctx, next) {
    const { momentId } = ctx.params;
    const { content } = ctx.request.body;
    const result = await momentService.update(content, momentId);

    ctx.body = {
      code: 0,
      message: "更新成功",
      data: result,
    };
  }

  async addLabels(ctx, next) {
    const { labels } = ctx;
    const { momentId } = ctx.params;

    try {
      for (const label of labels) {
        const isExists = await momentService.hasLabel(momentId, label.id);
        if (!isExists) {
          await momentService.addLabel(momentId, label.id);
        }
      }

      ctx.body = {
        code: 0,
        message: "为动态添加标签成功~",
      };
    } catch (err) {
      ctx.body = {
        code: -3001,
        message: "添加标签失败",
      };
    }
  }
}

module.exports = new MomentController();
